package cn.bytecollege.admin.filter;

import cn.bytecollege.admin.service.AdminService;
import cn.bytecollege.common.constant.Resource;
import cn.bytecollege.common.entity.Admin;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginVerifyFilter",value = "/admin/*")
public class LoginVerifyFilter implements Filter {
    private AdminService adminService= null;
    public LoginVerifyFilter(){
        adminService = new AdminService();
    }
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        String uri  = req.getRequestURI();
        if (uri.contains("login.jsp")||uri.contains("/admin/adminLogin")||uri.contains("/valid")){
            chain.doFilter(request,response);
            return;
        }
        HttpSession session = req.getSession();
        Admin admin = (Admin) session.getAttribute("admin");
        if(admin==null){
            //没有登录
            String msg = null;
            msg = "请先登录";
            request.setAttribute("msg",msg);
            request.getRequestDispatcher(Resource.PAGE_LOCATION+"/admin/login.jsp")
                    .forward(request,response);
            return;
        }

        Admin adminSession = (Admin) session.getAttribute("admin");
        String username = adminSession.getAdminUsername();
        Admin admin1=adminService.findAdminByAdminId(username);
        session.setAttribute("admin",admin1);
        chain.doFilter(request, response);
    }
}
